<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
            
            /*
                $dataTree=array(
                        array(
                                'text'=>'Grampa', //must using 'text' key to show the text
                                'children'=>array(//using 'children' key to indicate there are children
                                        array(
                                                'text'=>'Father',
                                                'children'=>array(
                                                        array('text'=>'me'),
                                                        array('text'=>'big sis'),
                                                        array('text'=>'little brother'),
                                                )
                                        ),
                                        array(
                                                'text'=>'Uncle',
                                                'children'=>array(
                                                        array('text'=>'Ben'),
                                                        array('text'=>'Sally'),
                                                )
                                        ),
                                        array(
                                                'text'=>'Aunt',
                                        )
                                )
                        )
                );*/
                $model = new LoginForm;
                if(isset($_POST['LoginForm']))
                {
                        $model->attributes=$_POST['LoginForm'];
                        // validate user input and redirect to the previous page if valid
                        if($model->validate() && $model->login())
                                $this->redirect(Yii::app()->user->returnUrl);
                }
                
		$this->render('index');
	}
        
        public function actionSearch($keyword){
                if(isset($_GET['submit'])){
                        $criteria=new CDbCriteria();
                        $criteria->compare('name', $keyword, true);
                        $criteria->compare('monhocId', $_GET['mhid']);
                        $criteria->compare('khoihocId', $_GET['khid']);
                        $criteria->compare('monhocChildId', $_GET['mhcid']);

                        $dataProvider=new CActiveDataProvider('BaiGiang', array(
                                'criteria'=>$criteria,
                                'pagination'=>array(
                                        'pageSize'=>9
                                )
                        ));

                        $this->render('search_result', array(
                                'dataProvider'=>$dataProvider,
                                'keyword'=>$keyword
                        ));
                }else{
                        $this->redirect(array('site/index'));
                }
        }
        
        public function actionGetMonHocChildSelectHtmlOptions($monhocId){
                $monhocChildModels=  MonHocChild::model()->findAllByAttributes(array('monhocId'=>$monhocId));
                
                if(!empty($monhocChildModels)){
                        echo '<option value="">Tất cả</option>';
                        foreach ($monhocChildModels as $model){
                                echo '<option value=' . $model->id . '>' . $model->name . '</option>' ;
                        }
                }
        }
        
        public function getFolderTreeData(){
                $dataTree=array();
            
                $monhocModels=  MonHoc::model()->findAll();
                
                foreach($monhocModels as $monhoc){
                        $monhocTree=array('text'=>$monhoc->name);
                        
                        $mohocTreeChildren=array();
                        
                        $khoihocs=Yii::app()->db->createCommand()
                                ->selectDistinct('khoihoc.name as name, khoihoc.id as id')
                                ->from('khoihoc')
                                ->join('baigiang', 'baigiang.khoihocId=khoihoc.id')
                                ->where('baigiang.monhocId=:monhocId', array(':monhocId'=>$monhoc->id))
                                ->order('khoihoc.name asc')
                                ->queryAll();
                        
                        $monhocChildModels=$monhoc->getMonhocChilds();
                        
                        foreach($khoihocs as $kh){
                                $khtree=array('text'=>$kh['name']);
                                
                                $khtreeChildren=array();
                                
                                if(!empty($monhocChildModels)){
                                        foreach($monhocChildModels as $mhChildModel){
                                                $baigiangCount=  BaiGiang::model()->countByAttributes(array(
                                                        'monhocId'=>$monhoc->id,
                                                        'khoihocId'=>$kh['id'],
                                                        'monhocChildId'=>$mhChildModel->id
                                                ));
                                                
                                                if($baigiangCount>0){
                                                        $mhChildTree=array(
                                                                'text'=>$mhChildModel->name,
                                                                'htmlOptions'=>array(
                                                                        'href'=>Yii::app()->createUrl('site/searchBaiGiangByMonHocChild', array('monhocId'=>$monhoc->id, 'khoihocId'=>$kh['id'], 'monhocChildId'=>$mhChildModel->id)),
                                                                        'class'=>'tree-searchable-item'
                                                                )
                                                        );
                                                        
                                                        $khtreeChildren[]=$mhChildTree;
                                                }
                                                /*
                                                $baigiangModels=  BaiGiang::model()->findAllByAttributes(array(
                                                        'monhocId'=>$monhoc->id,
                                                        'khoihocId'=>$kh['id'],
                                                        'monhocChildId'=>$mhChildModel->id
                                                ));
                                                
                                                if(!empty($baigiangModels)){
                                                        $mhChildTree=array(
                                                                'text'=>$mhChildModel->name                                                                
                                                        );
                                                        
                                                        $children=array();
                                                        
                                                        foreach($baigiangModels as $baigiang){
                                                                $children[]=array(
                                                                        'text'=>$baigiang->name
                                                                );
                                                        }
                                                        
                                                        $mhChildTree['children']=$children;
                                                        
                                                        $khtreeChildren[]=$mhChildTree;
                                                }*/
                                        }
                                        
                                        $khtree['children']=$khtreeChildren;
                                }else{
                                        $khtree['hasChildren']=false;
                                        $khtree['htmlOptions']=array(
                                                'href'=>Yii::app()->createUrl('site/searchBaiGiangByKhoiHoc', array('monhocId'=>$monhoc->id, 'khoihocId'=>$kh['id'])),
                                                'class'=>'tree-searchable-item'
                                        );
                                }
                                
                                $mohocTreeChildren[]=$khtree;
                        }
                    
                        if(!empty($mohocTreeChildren)){
                                $monhocTree['children']=$mohocTreeChildren;
                        }else{
                                $monhocTree['hasChildren']=false;
                        }
                        
                        $dataTree[]=$monhocTree;
                }
                
                return $dataTree;
        }
        
        public function actionSearchBaiGiangByKhoiHoc($monhocId, $khoihocId){
                $criteria=new CDbCriteria();
                $criteria->compare('monhocId', $monhocId);
                $criteria->compare('khoihocId', $khoihocId);
                
                $dataProvider=new CActiveDataProvider('BaiGiang', array(
                        'criteria'=>$criteria,
                        'pagination'=>array(
                                'pageSize'=>9
                        )
                ));
                
                $monhoc=  MonHoc::model()->findByPk($monhocId);
                $khoihoc=  KhoiHoc::model()->findByPk($khoihocId);
                
                $this->breadcrumbs=array(
                        $monhoc->name=>array('site/listByMonHoc', 'id'=>$monhocId),
                        $khoihoc->name=>array('site/listByKhoiHoc', 'id'=>$khoihocId)
                );
                
                $this->renderPartial('search_baigiang_results', array(
                        'title'=>$monhoc->name . '-' . $khoihoc->name,
                        'dataProvider'=>$dataProvider
                ));
        }
        
        public function actionSearchBaiGiangByMonHocChild($monhocId, $khoihocId, $monhocChildId){
                           
                $criteria=new CDbCriteria();
                $criteria->compare('monhocId', $monhocId);
                $criteria->compare('khoihocId', $khoihocId);
                $criteria->compare('monhocChildId', $monhocChildId);
                
                $dataProvider=new CActiveDataProvider('BaiGiang', array(
                        'criteria'=>$criteria,
                        'pagination'=>array(
                                'pageSize'=>9
                        )
                ));
                
                $monhoc=  MonHoc::model()->findByPk($monhocId);
                $khoihoc=  KhoiHoc::model()->findByPk($khoihocId);
                $monhocChild=  MonHocChild::model()->findByPk($monhocChildId);
                
                $this->breadcrumbs=array(
                        $monhoc->name=>array('site/listByMonHoc', 'id'=>$monhocId),
                        $khoihoc->name=>array('site/listByKhoiHoc', 'monhocId'=>$monhocId, 'khoihocId'=>$khoihocId),
                        $monhocChild->name=>array('site/listByMonHocChild', 'khoihocId'=>$khoihocId, 'monhocChildId'=>$monhocChildId)
                );
                
                $this->renderPartial('search_baigiang_results', array(
                        'title'=>$monhoc->name . '-' . $khoihoc->name . '-' . $monhocChild->name,
                        'dataProvider'=>$dataProvider
                ));
        }
        
        public function actionListByMonHoc($id){
                $criteria=new CDbCriteria();
                $criteria->compare('monhocId', $id);
                
                $dataProvider=new CActiveDataProvider('BaiGiang', array(
                        'criteria'=>$criteria,
                        'pagination'=>array(
                                'pageSize'=>9
                        )
                ));
                
                $monhoc=  MonHoc::model()->findByPk($id);
                
                $this->breadcrumbs=array(
                        $monhoc->name=>array('site/listByMonHoc', 'id'=>$id)
                );
                
                $this->render('list_baigiang_results', array(
                        'dataProvider'=>$dataProvider,
                        'searchResultTitle'=>$monhoc->name
                ));
        }
        
        public function actionListByKhoiHoc($monhocId, $khoihocId){
                $criteria=new CDbCriteria();
                $criteria->compare('monhocId', $monhocId);
                $criteria->compare('khoihocId', $khoihocId);
                
                $dataProvider=new CActiveDataProvider('BaiGiang', array(
                        'criteria'=>$criteria,
                        'pagination'=>array(
                                'pageSize'=>9
                        )
                ));
                
                $khoihoc=  KhoiHoc::model()->findByPk($khoihocId);
                $monhoc=  MonHoc::model()->findByPk($monhocId);
                
                $this->breadcrumbs=array(
                        $monhoc->name=>array('site/listByMonHoc', 'id'=>$monhocId),
                        $khoihoc->name=>array('site/listByKhoiHoc', 'monhocId'=>$monhocId, 'khoihocId'=>$khoihocId)
                );
                
                $this->render('list_baigiang_results', array(
                        'dataProvider'=>$dataProvider,
                        'searchResultTitle'=>$monhoc->name . '-' . $khoihoc->name
                ));
        }
        
        public function actionListByMonHocChild($khoihocId, $monhocChildId){
                $criteria=new CDbCriteria();
                $criteria->compare('monhocChildId', $monhocChildId);
                $criteria->compare('khoihocId', $khoihocId);
                
                $dataProvider=new CActiveDataProvider('BaiGiang', array(
                        'criteria'=>$criteria,
                        'pagination'=>array(
                                'pageSize'=>2
                        )
                ));
                
                $monhocChild=  MonHocChild::model()->findByPk($monhocChildId);
                $khoihoc=  KhoiHoc::model()->findByPk($khoihocId);
                $monhoc=  MonHoc::model()->findByPk($monhocChild->monhocId);
                
                $this->breadcrumbs=array(
                        $monhoc->name=>array('site/listByMonHoc', 'id'=>$monhoc->id),
                        $khoihoc->name=>array('site/listByKhoiHoc', 'monhocId'=>$monhoc->id, 'khoihocId'=>$khoihocId),
                        $monhocChild->name=>array('site/listByMonHocChild', 'khoihocId'=>$khoihocId, 'monhocChildId'=>$monhocChildId)
                );
                
                $this->render('list_baigiang_results', array(
                        'dataProvider'=>$dataProvider,
                        'searchResultTitle'=>$monhoc->name . '-' . $khoihoc->name . '-' .$monhocChild->name
                ));
        }
        
        public function actionViewBaiGiang($id){
                $baigiangModel=  BaiGiang::model()->findByPk($id);
                
                if($baigiangModel){
                        $this->render('bai_giang_view', array('model'=>$baigiangModel));
                }else{
                        throw new CHttpException(404, 'Đường dẫn không chính xác');
                }
        }

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
				$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
				$headers="From: $name <{$model->email}>\r\n".
					"Reply-To: {$model->email}\r\n".
					"MIME-Version: 1.0\r\n".
					"Content-type: text/plain; charset=UTF-8";

				mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}